package com.uniview.interceptor;

import com.uniview.eumn.CommonEnum;
import com.uniview.exception.CommonException;
import com.uniview.orm.model.SysUser;
import com.uniview.util.ThreadUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author lux
 * @date: 2019/11/26
 * @desc: 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //token存在header中
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            throw new CommonException(CommonEnum.TOKEN_EMPTY_CODE, CommonEnum.TOKEN_EMPTY_MSG);
        }
        ThreadUtils.setToken(token);
        //根据token获取redis信息
        SysUser sysUser = (SysUser) redisTemplate.opsForValue().get(token);
        ThreadUtils.setUserHolder(sysUser);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {
        ThreadUtils.remove();
    }
}
